package com.glorystone.ins.controller;

import com.fastdfs.FastDFSClient;
import com.glorystone.ins.common.JsonResult;
import com.glorystone.ins.domain.Attachment;
import com.glorystone.ins.service.AttachmentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import java.io.UnsupportedEncodingException;
import java.util.List;

/**
 * Created by wangwei on 2018/3/28.
 */
@Controller
@RequestMapping("/attachment")
public class AttachmentController extends BaseController {

    @Autowired
    private AttachmentService attachmentService;
    @Autowired
    private FastDFSClient fastDFSClient;


    @RequestMapping(value = "/{businessType}/{businessId}", method = RequestMethod.GET)
    public ResponseEntity<List<Attachment>> findAll(@PathVariable("businessType") Integer businessType, @PathVariable("businessId") Long businessId) {

        List<Attachment> list = attachmentService.queryAttachList(businessId, businessType);

        return new ResponseEntity<List<Attachment>>(list, HttpStatus.OK);
    }


    @RequestMapping("/download/{tid}")
    public ResponseEntity<byte[]> download(@PathVariable("tid") Long tid) throws UnsupportedEncodingException {

        Attachment file = attachmentService.findById(tid);
        byte[] b = fastDFSClient.downloadFile(file.getUrl());

        HttpHeaders headers = new HttpHeaders();
        String fileName = new String(file.getName().getBytes("UTF-8"), "iso-8859-1");
        headers.setContentDispositionFormData("attachment", fileName);
        headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
        return new ResponseEntity<byte[]>(b, headers, HttpStatus.OK);

    }


    @ResponseBody
    @RequestMapping(value = "/delete/{tid}", method = RequestMethod.GET)
    public ResponseEntity<JsonResult> delete(@PathVariable Long tid) {
        attachmentService.delete(tid);
        return new ResponseEntity<>(JsonResult.createSuccess(), HttpStatus.OK);

    }

}
